//
// Created by 45595 on 2021/10/4.
//

#include <bits/stdc++.h>

using namespace std;

const int MAXN = 100010;

struct node{
    char data;
    int next;
    bool flag;
}nodes[MAXN];

int main() {
    freopen("../A1032.txt", "r", stdin);
    int s1,s2,n;
    cin>>s1>>s2>>n;
    for(int i=0;i<MAXN;i++){
        nodes[i].flag = false;
    }

    int address,next;
    char data;
    for(int i=0;i<n;i++){
        cin>>address>>data>>next;
        nodes[address].data = data;
        nodes[address].next = next;
    }

    int p;
    for(p=s1;p!=-1;p=nodes[p].next){
        nodes[p].flag = true;
    }
    for(p=s2;p!=-1;p=nodes[p].next){
        if(nodes[p].flag) break;
    }

    if(p!=-1){
        printf("%05d\n",p);
    }else{
        cout<<-1<<endl;
    }

    return 0;
}